package com.example.annotation.reflect;

import com.google.common.collect.Sets;
import lombok.Data;

import java.lang.reflect.Method;
import java.util.Set;

public class RequestMappingParser<T> {
    private final Class<T> tClass;

    public RequestMappingParser(Class<T> tClass){
        this.tClass = tClass;
    }

    public Set<ParserResult> parse(){
        RequestMapping cRequestMapping = this.tClass.getAnnotation(RequestMapping.class);
        String rootPath = cRequestMapping != null ? cRequestMapping.path() : "";
        if (!rootPath.startsWith("/")){
            rootPath = "/" + rootPath;
        }

        Set<ParserResult> parserResults = Sets.newHashSet();
        for (Method method : this.tClass.getMethods()){
            RequestMapping mRequestMapping = method.getAnnotation(RequestMapping.class);
            if (mRequestMapping == null){
                continue;
            }

            String mPath = mRequestMapping.path();
            if ("".equals(mPath)){
                continue;
            }
            String path = null;
            if (mPath.startsWith("/")){
                path = rootPath + mPath;
            }else {
                path = rootPath + "/" + mPath;
            }
            parserResults.add(new ParserResult(path, method));
        }
        return parserResults;
    }


    @Data
    static class ParserResult{
        private final String path;
        private final Method method;
    }
}
